package main

import (
	"fmt"
	"github.com/iGoogle-ink/gopay"
	"github.com/iGoogle-ink/gopay/wechat"
	"github.com/iGoogle-ink/gotil"
	"github.com/iGoogle-ink/gotil/xlog"
	"strconv"
	"time"
)

var (
	client *wechat.Client
	appId  = "wxdaa2ab9ef87b5497"
	mchId  = "1368139502"
	apiKey = "GFDS8j98rewnmgl45wHTt980jg543abc"
)

var TradeType_Mini   = "JSAPI"  // 小程序支付
var SignType_MD5         = "MD5"

func main() {
	// 初始化微信客户端
	//    appId：应用ID
	//    mchId：商户ID
	//    apiKey：API秘钥值
	//    isProd：是否是正式环境
	client = wechat.NewClient(appId, mchId, apiKey, false)
	//设置国家，不设置就默认中国
	client.SetCountry(wechat.China)

	TestClient_UnifiedOrder()
}


func TestClient_UnifiedOrder() {
	number := gotil.GetRandomString(32)
	xlog.Info("out_trade_no:", number)
	// 初始化参数Map
	bm := make(gopay.BodyMap)
	bm.Set("nonce_str", gotil.GetRandomString(32))
	bm.Set("body", "小程序支付")
	bm.Set("out_trade_no", number)
	bm.Set("total_fee", 1)
	bm.Set("spbill_create_ip", "127.0.0.1")
	bm.Set("notify_url", "http://www.gopay.ink")
	bm.Set("trade_type", TradeType_Mini)
	bm.Set("device_info", "小程序")
	bm.Set("sign_type", SignType_MD5)
	//沙箱
	wechat.GetSanBoxParamSign("wxdaa2ab9ef87b5497", "1368139502", "GFDS8j98rewnmgl45wHTt980jg543abc", bm)

	// 请求支付下单，成功后得到结果
	wxRsp, err := client.UnifiedOrder(bm)
	if err != nil {
		//xlog.Errorf("client.UnifiedOrder(%+v),error:%+v", bm, err)
		fmt.Println(err)
		return
	}
	xlog.Info("wxRsp:", *wxRsp)
	//生成时间戳
	timeStamp := strconv.FormatInt(time.Now().Unix(), 10)
	// 获取小程序支付需要的paySign
	pac := "prepay_id=" + wxRsp.PrepayId
	paySign := wechat.GetMiniPaySign(appId, wxRsp.NonceStr, pac, SignType_MD5, timeStamp, apiKey)
	xlog.Info("paySign:", paySign)

}